<!--
   Copyright 2020-2021 the original author or authors.

   Licensed under the General Public License, Version 3.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

        https://www.gnu.org/licenses/gpl-3.0.en.html
 -->

<template>
  <div class="box clearfix">
      <div class="title">
          <span>Welcome to ZZUOJ</span>
      </div>
      <div class="box-main">
        <Form ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          label-position="right"
          :label-width="95"
          label-colo>
          <FormItem prop="username" label="用户名">
            <Input v-model="loginForm.username" placeholder="用户名" />
          </FormItem>
          <FormItem prop="password" label="密码">
            <Input type="password" v-model="loginForm.password" placeholder="密码" @on-enter="handleLogin('loginForm')"/>
          </FormItem>
        </Form>
      </div>
      <div class="bottom">
        <div class="btns">
          <div>
            <router-link :to="{ name: 'reset-password' }">忘记密码</router-link>
          </div>
          <Button type="text"
            @click="handleLogin('loginForm')"
            :loading="btnLoginLoading">登录</Button>
        </div>
      </div>
  </div>
</template>

<script>
import api from '_u/api';
import { mapActions } from 'vuex';

export default {
  data: function() {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [
          { required: true, trigger: 'blur' }
        ],
        password: [
          { required: true, trigger: 'blur', min: 6, max: 32 }
        ]
      },
      btnLoginLoading: false
    }
  },
  methods: {
    ...mapActions('user', ['setProfile', 'setLogin']),
    handleLogin: function(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          api.login(this.loginForm).then(ret => {
            this.setProfile(ret);
            this.$router.replace(this.$route.query.to || '/');
          }).catch(err => {
            this.$Message.error(err.message);
          });
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.box {
  width: 400px;
  padding: 20px;
  margin: 30px auto 0;
  background-color: #fff;
  border-radius: 5px;
}

.title {
  margin-bottom: 10px;
  text-align: center;
  color: #22aa55;
  font-size: 24px;
  font-weight: bold;
}

.box-main {
  padding: 10px;
}

/deep/.ivu-form-item-content {
  margin: 0;
}

/deep/ .ivu-input.ivu-input-default {
  width: 220px;
}
.btns {
  width: 50%;
  margin: 10px auto;
  display: flex;
  justify-content: space-around;
  align-items: center;
  .ivu-btn:hover {
    background: rgba(0, 0, 0, 0.05);
  }
  a {
    color: #000;
    text-decoration: underline;
    margin-right: 8px;
  }
}

.captcha-img {
  margin-top: 5px;
}

.bottom {

}
</style>
